package com.portal.service.impl;

import com.portal.dao.CityMapper;
import com.portal.pojo.City;
import com.portal.service.CityService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class CityServiceImpl implements CityService {
    private static final Logger LOGGER=LoggerFactory.getLogger(CityServiceImpl.class);
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CityMapper cityMapper;
    @Override
    public City selectCity(int id) {
        String key="city:"+id;
        ValueOperations<String,City> operations=redisTemplate.opsForValue();
        if(redisTemplate.hasKey(key)){
            City city = operations.get(key);
            LOGGER.info("缓存获取了 city"+city.toString());
            return city;
        }
        City city = cityMapper.selectCity(id);
        operations.set(key,city,30, TimeUnit.SECONDS);
        LOGGER.info("数据库获取了 city"+city.toString());
        return city;
    }

    @Override
    public Long updateCity(City city) {
        Long re = cityMapper.updateCity(city);
        String key="city:"+city.getId();
       if( redisTemplate.hasKey(key)){
           redisTemplate.delete(key);
           LOGGER.info("从缓存中删除城市");
       }
      // int i=1/0;
       return re;
    }
}
